using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;

namespace Moogle
{
    /// <summary>
    /// OTC Add Activity Class.  This activity is used to add over the counter (OTC) medications to the
    /// the user list of prescribed medications.  It's target consumer is the ActivityOTCUpdate class.
    /// </summary>
    [Activity(Label = "Add OTC Medication", MainLauncher = false, Icon = "@drawable/icon", Theme = "@android:style/Theme.Holo.Light", NoHistory=true)]
    [IntentFilter(new[] { Intent.ActionMain })]
    public class ActivityOTCAdd : Activity
    {
        #region Local Memory
        private MedicationListAdapter __MedicationListAdapter;
        /// <summary>
        /// Constant using to identify (filter) entries created in the
        /// Android Log by this class.
        /// </summary>
        private const string __C_TAG = "ActivityOTCAdd";
        /// <summary>
        /// Constant string value defining the filename where the user's
        /// medication information is stored.  This file has 
        /// a CSV format--
        /// [TYPE],[MEDICATION NAME]
        /// </summary>
        private const string __C_MEDICATIONS_FILENAME = "medications.csv";
        /// <summary>
        /// List object used to store Rx Selections extracted from
        /// the prescribed_medications.csv file.
        /// </summary>
        private List<Medication> __listRxSelections = new List<Medication>();
        /// <summary>
        /// List object used to store OTC Selections extracted from
        /// the prescribed_medications.csv file.
        /// </summary>
        private List<Medication> __listOTCSelections = new List<Medication>();
        #endregion
        #region OnCreate Control Function

        /// <summary>
        /// Class (or Activity) entry point.
        /// </summary>
        /// <param name="bundle">Android.OS.Bundle object instance that can be used to pass data to activity at startup.</param>
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Log.Info(__C_TAG, "OnCreate started.");

            try
            {
                /// Set the content view
                SetContentView(Resource.Layout.otcadd);

                /// Initialize a List View based on the List View 
                /// defined layout for the screen
                ListView _listView = FindViewById<ListView>(Resource.Id.listView);
                /// Set the ChoiceMode to "Multiple"
                _listView.ChoiceMode = 2;
                /// Configure the Cancel Button
                #region ...
                Button _buttonCancel = FindViewById<Button>(Resource.Id.doBack);
                _buttonCancel.Click += delegate
                {
                    var _IntentShow = new Intent(this, typeof(ActivityLearn));
                    StartActivity(_IntentShow);
                };
                #endregion

                /// Populate the otc list based
                /// on the "medications_csv"
                #region ...

                dbCommands _clsDbCommands = new dbCommands(this);
                IList<Medication> _colAllMedcations = _clsDbCommands.GetAllPrescribedMedication();

               
                    string _path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    Log.Debug(__C_TAG, _path);
                    string _filename = Path.Combine(_path, __C_MEDICATIONS_FILENAME);

                    if (File.Exists(_filename))
                    {
                        /// Read the contents of the prescriptions info file
                        /// into a List Object
                        #region ...
                        String[] _strArrDelimiters = { "," };

                        using (var _f = new StreamReader(OpenFileInput(__C_MEDICATIONS_FILENAME)))
                        {
                            string _line;
                            do
                            {
                                _line = _f.ReadLine();
                                String[] _strValues = _line.Split(_strArrDelimiters, StringSplitOptions.RemoveEmptyEntries);
                                int _id = 1;
                                if (null != _strValues && _strValues.Length == 2)
                                {
                                    Medication _Med = new Medication();
                                    _Med.MedicationID = _id;
                                    _Med.Name = _strValues[1];
                                    _Med.Type = _strValues[0];

                                    switch (_strValues[0].Trim().ToUpper())
                                    {
                                        case "OTC":
                                            if (null != _colAllMedcations &&
                                                _colAllMedcations.Count > 0)
                                            {
                                                if(!_clsDbCommands.ContainsMedicationName(_Med.Name) &&
                                                    !__listOTCSelections.Contains(_Med))
                                                    __listOTCSelections.Add(_Med);
                                            } // end if
                                            else if ( !__listOTCSelections.Contains(_Med))
                                                __listOTCSelections.Add(_Med);
                                            break;
                                    } // end switch
                                    _id++;
                                } // end if
                            } while (!_f.EndOfStream);
                        } // end using
                        #endregion
                    } // end if
                

                #endregion

                /// If the OTC Selection is not empty, then
                /// use it to populate the list view control.
                #region ...
                if (this.__listOTCSelections.Count > 0)
                {
                    Log.Debug(__C_TAG, "Configuring MedicationListAdapter...");
                    this.__MedicationListAdapter = new MedicationListAdapter(this, __listOTCSelections,false);
                    _listView.Adapter = this.__MedicationListAdapter;

                } // end if
                #endregion

                /// Configure the Update Button
                /// click delegate using the
                /// fully qualified filename
                #region ...
                Button _buttonUpdate = FindViewById<Button>(Resource.Id.doUpdate);
                _buttonUpdate.Click += delegate
                {
                    this.OnDoUpdate();
                    var _IntentShow = new Intent(this, typeof(ActivityOTCUpdate));
                    StartActivity(_IntentShow);
                }; // end delegate
                #endregion
               

            } // end try
            catch (SystemException err)
            {
                Log.Error(__C_TAG, err.StackTrace);
            } // end catch
            finally
            {
                Log.Info(__C_TAG, "OnCreate ended.");
            } // end finally
        }

        #endregion
        #region Update File Process

        /// <summary>
        /// Method used to update the prescribed_medications.csv
        /// based on the contents of the RX and OTC List objects.
        /// </summary>
        private void OnDoUpdate()
        {
            Log.Info(__C_TAG, "OnDoUpdate started.");

            try
            {
                /// Delete all Rx and OTC medications from the
                /// PrescribedMedications Table

                Log.Debug(__C_TAG, "Clearing current OTC Medications from database...");
                var _clsDbCmds = new dbCommands(this);
                _clsDbCmds.DeleteMedicationType("OTC");
             
                if (null != this.__MedicationListAdapter)
                {
                    foreach (Medication _clsSelOtc in this.__listOTCSelections)
                    {
                        if (null != this.__MedicationListAdapter &&
                            this.__MedicationListAdapter.MedicationNameSelections.Contains(_clsSelOtc.Name))
                        {
                            Log.Info(__C_TAG, "Adding - \"OTC," + _clsSelOtc.Name + "\"");
                            _clsDbCmds.AddMedication(_clsSelOtc.Type, _clsSelOtc.Name);
                        } // end if
                    } // end foreach
                } // end if

            } // end try
            catch (SystemException err)
            {
                Log.Error(__C_TAG, err.Message);
            } // end catch
            finally
            {
                Log.Info(__C_TAG, "OnDoUpdate ended.");
            } // end finally
        }

        #endregion
    }
}